package com.study.mybatis.binding;

import com.study.mybatis.session.SqlSession;

import java.lang.reflect.Proxy;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class MapperProxyFactory<T> {

    private final Class<T> interfaces;

    public MapperProxyFactory(Class<T> interfaces) {
        this.interfaces = interfaces;
    }

    public T getMapperProxy(SqlSession sqlSession){
        MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession,interfaces);
        return newInstance(mapperProxy);
    }

    /**
     * 生成UserMapper的代理对象，最后再mapperProxy的invoke方法中去执行UserMapper中方法
     */
    public T newInstance(MapperProxy<T> mapperProxy){
        return (T) Proxy.newProxyInstance(interfaces.getClassLoader(), new Class<?>[]{interfaces}, mapperProxy);
    }

}
